<template>
  <el-row class="login-container" justify="center" :align="`middle`">
    <el-card style="max-width: 480px;">
      <template #header>
        <div class="card-title">
          <img :src="imgUrl" alt="hh" style="width: 400px"/>
<!--          <p style="margin: 0 auto">欢迎用户登录</p>-->
        </div>
      </template>
      <div style="text-align: right;margin-bottom: 10px">
        <el-link type="primary" @click="handleChange">{{formType?'返回登录' :'注册账号'}}</el-link>
      </div>
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" >
        <el-form-item prop="userName">
          <el-input  v-model="loginForm.userName" placeholder="手机号" :prefix-icon="User"></el-input>
        </el-form-item>
        <el-form-item prop="passWord">
          <el-input v-model="loginForm.passWord" placeholder="密码" type="password" :prefix-icon="Lock"></el-input>
        </el-form-item>
        <el-form-item v-if="formType" prop="validCode" >
          <el-input
              v-model="loginForm.validCode"
              placeholder="验证码"
              :prefix-icon="Lock"
          >
            <template #append>
              <span @click="handleSend" style="cursor: pointer">{{validCode.text}}</span>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <el-button style="width: 100%" type="primary" @click="handleCommit(loginFormRef)">
        {{formType?'注册账号':'登录'}}
      </el-button>

    </el-card>
  </el-row>

</template>

<script setup>
import {ref,reactive,computed,toRaw} from "vue";
import {User,Lock} from "@element-plus/icons-vue";
import {getCode,userAuthentication,login,menuPermissions} from "../api/index.js";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import {useMenuStore} from "../stores/menu.js"

const router = useRouter();
const imgUrl = new URL("../assets/header.png",import.meta.url).href;
//获取menuStore
const menuStore = useMenuStore();
//登录表单
const loginForm = reactive({
  userName: '',
  passWord: '',
  validCode:'',
})

// 表单实例
const loginFormRef = ref(null);
const validateMobile = (rule, value, callback) => {
  const reg = /^1[3-9]\d{9}$/
  if (!reg.test(value)) {
    callback(new Error('手机号格式不正确'))
  } else {
    callback()
  }
}

//路由数据
const routerList = computed(()=>menuStore.routerList)
//登录表单验证
const loginRules = reactive({
  userName: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {validator: validateMobile,trigger:'blur'}
  ],
  passWord: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
  ],
  validCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ]
})


//0代表登录，1代表注册
const formType = ref(0);
//切换登录注册页面
const handleChange = () => {
  formType.value = formType.value === 0 ? 1 : 0;
}

const validCode = reactive({
  text: '获取验证码',
  time: 60,
  flag:false
})
let timer=null;
const handleSend = () => {
  //判断计时器是否已存在
  if(validCode.flag) return
  //判断手机号是否正确
  const reg = /^1[3-9]\d{9}$/
  if(!loginForm.userName){
    ElMessage.error('请输入手机号')
    return
  }else if (!reg.test(loginForm.userName)) {
    ElMessage.error('手机号格式不正确')
    return
  }



  validCode.flag = true;
  validCode.time = 60;
  validCode.text = `剩余${validCode.time}s`;

  timer = setInterval(() => {
    validCode.time -= 1;
    if(validCode.time <= 0){
      clearInterval(timer); // 清除定时器
      validCode.text = '获取验证码';
      validCode.flag = false;
    } else {
      validCode.text = `剩余${validCode.time}s`;
    }
  }, 1000)

  getCode({tel:loginForm.userName}).then(({data})=>{
    if(data.code === 10000){
      ElMessage.success(data.message);
    } else {
      ElMessage.error(data.message);
      clearInterval(timer);
    }
  })
}

//表单提交
const handleCommit = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      //判断是登录还是注册
      if(formType.value){
        userAuthentication(loginForm).then(({data}) => {
          if(data.code === 10000){
            ElMessage.success('注册成功')
            formType.value=0;
          } else {
            ElMessage.error(data.message);
          }
        })
      }else{
        login(loginForm).then(({data})=>{
          if(data.code === 10000){
            console.log(data)
            //将token以及用户信息缓存到localStorage
            localStorage.setItem('pz_token',data.data.token)
            localStorage.setItem('pz_userInfo',JSON.stringify(data.data.userInfo))
            menuPermissions().then(({data})=>{
              menuStore.dynamicMenu(data.data)
              toRaw(routerList.value).forEach(item=>{
                router.addRoute('manager',item)
              })
              router.push('/')
            })

            ElMessage.success('登录成功')
          } else {
            ElMessage.error(data.message);
          }
        })

      }
    } else {
      console.log('error submit!', fields)
    }
  })

}

</script>

<style scoped>
.el-form-item__content {
  margin-left: 0;
}

.login-container{
  height: 100vh;
  align-items: center;
  .card-title{
    align-items: center;
    margin: 0 auto;
    background-color: #e9f7ff;
  }



}

</style>
